import {
  GeoJsonDataSource,
  Color,
  JulianDate,
  BoundingSphere,
  Cartesian3,
  Cartesian2,
  Cartographic,
  Ellipsoid,
  Math,
  NearFarScalar
} from 'cesium'
import { queryFeatures } from '@esri/arcgis-rest-feature-service'
import mapConfig from '../../mapConfig'

const addGeoJsonData = async (viewer, opts = {}) => {
  const res = {}
  const url = opts.url + '&cql_filter=' + opts.where
  // &cql_filter=farm_id=47035753446400
  await fetch(url)
    .then(function (response) {
      res.response = response
      console.log('response', response)
      return response.json()
    })
    .then(function (json) {
      res.features = json
      const promise = GeoJsonDataSource.load(json, {
        fill: Color.WHITE.withAlpha(0.3),
        stroke: Color.WHITE.withAlpha(0.3),
        strokeWidth: 1
      })
      console.log('res.features', res.features)
      promise
        .then(datasource => {
          viewer.dataSources.add(datasource)
          // 获取实体数组
          const entities = datasource.entities.values
          addLabel(viewer, entities)
        })
        .catch(error => {
          console.log(error)
        })
    })
    .catch(err => console.log('Request Failed', err))
  console.log('res', res)
  return res
}

const addArcGisFeatureServer = (viewer, opts = {}) => {
  mapConfig.fsParams.url = opts?.url
  mapConfig.fsParams.geometry.xmin = opts?.extent[0]
  mapConfig.fsParams.geometry.ymin = opts?.extent[1]
  mapConfig.fsParams.geometry.xmax = opts?.extent[2]
  mapConfig.fsParams.geometry.ymax = opts?.extent[3]
  const options = mapConfig.fsParams
  queryFeatures(options).then(response => {
    console.log('response', response)
    // const data = GeoJsonDataSource.load(response)
    // viewer.dataSources.add(data)
    const promise = GeoJsonDataSource.load(response, {
      fill: Color.WHITE.withAlpha(0.3),
      stroke: Color.WHITE.withAlpha(0.3),
      strokeWidth: 1
    })
    promise
      .then(datasource => {
        viewer.dataSources.add(datasource)
        // 获取实体数组
        const entities = datasource.entities.values
        addLabel(viewer, entities)
      })
      .catch(error => {
        console.log(error)
      })
  })
}

const addLabel = (viewer, entities) => {
  for (let i = 0; i < entities.length; i++) {
    const e = entities[i]
    const positions = e.polygon.hierarchy.getValue(JulianDate.now()).positions // 获取多边形当前时刻的顶点数组
    // 计算包围球并获取中心点
    const boundingSphere = BoundingSphere.fromPoints(positions)
    const centerPoint = boundingSphere.center // 这个centerPoint就是多边形大致的中心点
    // 将三维笛卡尔坐标转换为经纬度坐标,转换后的经纬度（单位为弧度）
    const cartographic = Cartographic.fromCartesian(
      centerPoint,
      Ellipsoid.WGS84
    )
    // 将弧度转换为度数
    const longitude_degrees = Math.toDegrees(cartographic.longitude)
    const latitude_degrees = Math.toDegrees(cartographic.latitude)
    viewer.entities.add({
      position: Cartesian3.fromDegrees(longitude_degrees, latitude_degrees),
      label: {
        text: e.name,
        font: '15px 微软雅黑',
        pixelOffset: new Cartesian2(0, 0), // 可选，像素偏移量以调整标签位置
        // translucencyByDistance: new NearFarScalar(1.0e2, 1.0, 1.5e4, 0.0),
        scaleByDistance: new NearFarScalar(0.0, 2.0, 1.0e4, 0.0)
      }
    })
  }
}

export { addGeoJsonData, addArcGisFeatureServer }
